package edu.ucdavis.genomics.metabolomics.binbase.mojo.updatesite;

import java.io.File;
import java.io.FileWriter;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
 * generates the site.xml file
 * 
 * @phase package
 * @goal create
 * @requiresProject true
 * @author wohlgemuth
 */
public class GenerateSiteXmlMojo extends AbstractMojo {
	/**
	 * Directory containing the build files.
	 * 
	 * @required
	 * @parameter expression="${project.build.directory}"
	 */
	private File buildDirectory;

	public GenerateSiteXmlMojo() {
		super();
	}

	public void execute() throws MojoExecutionException, MojoFailureException {
		getLog().info("creating site.xml file");
		File output = new File(getBuildDirectory().getAbsolutePath() + File.separator + "update-site" + File.separator + "site.xml");
		File features = new File(getBuildDirectory().getAbsolutePath() + File.separator + "update-site" + File.separator + "features");
		try {
			FileWriter writer = new FileWriter(output);

			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			writer.write("\n");

			writer.write("<site>");
			writer.write("\n");

			for (File feature : features.listFiles()) {
				getLog().info("found feature: " + feature);

				String url = "features/" + feature.getName();
				String id = feature.getName().substring(0, feature.getName().indexOf('_'));
				String version = feature.getName().substring(feature.getName().indexOf('_')+1, feature.getName().indexOf(".jar"));

				writer.write("<feature ");
				writer.write("url=\"");
				writer.write(url);
				writer.write("\" ");

				writer.write("id=\"");
				writer.write(id);
				writer.write("\" ");

				writer.write("version=\"");
				writer.write(version);
				writer.write("\" />");

				writer.write("\n");
			}

			writer.write("</site>");

			writer.flush();
			writer.close();
		}
		catch (Exception e) {
			throw new MojoExecutionException(e.getMessage(), e);
		}
	}

	public File getBuildDirectory() {
		return buildDirectory;
	}

}
